﻿/*
 * 由SharpDevelop创建。
 * 用户： Administrator
 * 日期: 2017/6/26
 * 时间: 23:45
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;

namespace TIDTool
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		const string AppName = "TID修改工具";
		const string AppVersion = "1.0";
		const string AppAuthor = "YanJingTu";
		const string AppBuildDate = "20170704";
		const string AppUpdateStr = "增加文件导出功能，增加替换文件功能";
		
		TidFile oneFile;
		
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			this.Text = AppName + 
				" v" + AppVersion + 
				"  by " + AppAuthor + 
				"  Build " + AppBuildDate + 
				"  --" + AppUpdateStr;
			
			oneFile = null;
		}
		
		void BtnLoadClick(object sender, EventArgs e)
		{
			TidFileReader tfr = new TidFileReader(tbTIDFile.Text);
			tfr.ReadAll();
			oneFile = tfr.tidFile;
			
			// 更新私有文件列表
			lvPrivateFileList.BeginUpdate();
			lvPrivateFileList.Clear();
//			int i = 0;
			foreach (KeyValuePair<TidPosition, byte[]> onefile in oneFile.PrivateFileList)
			{
//				i++;
				ListViewItem lvi = new ListViewItem();
				lvi.ImageIndex = 0;     //通过与imageList绑定，显示imageList中第i项图标
//				lvi.Text = "file" + i;
				lvi.Text = onefile.Key.fileNumber.ToString();
//				lvi.SubItems.Add("第2列,第"+i+"行");
//				lvi.SubItems.Add("第3列,第"+i+"行");
				lvPrivateFileList.Items.Add(lvi);
			}
			lvPrivateFileList.EndUpdate();
			
			// 更新公共文件列表
			lvPublicFileList.BeginUpdate();
			lvPublicFileList.Clear();
//			int i = 0;
			foreach (KeyValuePair<TidPosition, byte[]> onefile in oneFile.PublicFileList)
			{
//				i++;
				ListViewItem lvi = new ListViewItem();
				lvi.ImageIndex = 0;     //通过与imageList绑定，显示imageList中第i项图标
//				lvi.Text = "file" + i;
				lvi.Text = onefile.Key.fileNumber.ToString();
//				lvi.SubItems.Add("第2列,第"+i+"行");
//				lvi.SubItems.Add("第3列,第"+i+"行");
				lvPublicFileList.Items.Add(lvi);
			}
			lvPublicFileList.EndUpdate();
		}
		
		bool LvPrivateFileListGetSelectedMp3(out TidPosition pos, out byte[] fileData)
		{
			pos = new TidPosition(0, 0, 0);
			fileData = new byte[0];
			
			if (lvPrivateFileList.SelectedIndices.Count > 0)
			{
				int index = lvPrivateFileList.SelectedIndices[0];
				int i = 0;
				foreach (KeyValuePair<TidPosition, byte[]> onefile in oneFile.PrivateFileList)
				{
					if (index == i)
					{
						pos = onefile.Key;
						fileData = onefile.Value;
						break;
					}
					i++;
				}
				return true;
			}
			return false;
		}
		
		bool LvPrivateFileListSetSelectedMp3(byte[] fileData)
		{
			if (lvPrivateFileList.SelectedIndices.Count > 0)
			{
				int index = lvPrivateFileList.SelectedIndices[0];
				int i = 0;
				int oldBeginOffset = 0;
				foreach (KeyValuePair<TidPosition, byte[]> onefile in oneFile.PrivateFileList)
				{
					if (index == i)
					{
						oldBeginOffset = onefile.Key.beginOffset;
						oneFile.PrivateFileList[onefile.Key] = fileData;
						onefile.Key.fileLength = fileData.Length;
						break;
					}
					i++;
				}
				for (int j = 0; j < oneFile.PrivateInfoIndex.Count; j++)
				{
					if (oneFile.PrivateInfoIndex[j].beginOffset == oldBeginOffset)
					{
						oneFile.PrivateInfoIndex[j].fileLength = fileData.Length;
					}
				}
				return true;
			}
			return false;
		}
		
		void LvPrivateFileListPlaySelectedMp3()
		{
			TidPosition pos;
			byte[] fileData;
			if (LvPrivateFileListGetSelectedMp3(out pos, out fileData))
			{
				PlayOneMp3Data(pos.fileNumber, fileData);
			}
		}
		
		string GetOneSaveFilename(string title, string initDir, string defaultFilename, string defaultExtName, string filter)
		{
			string filename = "";
			
			sfdMain.Title = title;
			if (initDir.Length > 0)
				sfdMain.InitialDirectory = initDir;
			sfdMain.FileName = defaultFilename;
			sfdMain.DefaultExt = defaultExtName;
			sfdMain.Filter = filter;
			if (sfdMain.ShowDialog() == DialogResult.OK)
			{
				filename = sfdMain.FileName;
			}
			return filename;
		}
		
		string GetOneOpenFilename(string title, string initDir, string defaultFilename, string defaultExtName, string filter)
		{
			string filename = "";
			
			ofdMain.Title = title;
			if (initDir.Length > 0)
				ofdMain.InitialDirectory = initDir;
			ofdMain.FileName = defaultFilename;
			ofdMain.DefaultExt = defaultExtName;
			ofdMain.Filter = filter;
			if (ofdMain.ShowDialog() == DialogResult.OK)
			{
				filename = ofdMain.FileName;
			}
			return filename;
		}
		
		void LvPrivateFileListSaveSelectedMp3()
		{
			TidPosition pos;
			byte[] fileData;
			if (LvPrivateFileListGetSelectedMp3(out pos, out fileData))
			{
				string mp3Path = GetOneSaveFilename("导出文件", "", pos.fileNumber.ToString() + ".mp3", ".mp3", "MP3文件|*.mp3|所有文件|*.*");
				if (mp3Path.Length == 0)
					return;
			
				SaveOneMp3Data(mp3Path, fileData);
			}
		}
		
		public static void SaveOneMp3Data(string mp3Path, byte[] fileData)
		{
			BinaryWriter bw = new BinaryWriter(new FileStream(mp3Path, FileMode.OpenOrCreate));
			bw.Write(fileData);
			bw.Close();
		}
		
		public static void PlayOneMp3Data(int fileNumber, byte[] fileData)
		{
			string sTempDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
			sTempDir += "\\tidtool";
			Directory.CreateDirectory(sTempDir);
			string mp3Path = sTempDir + "\\" + fileNumber.ToString() + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".mp3";
			SaveOneMp3Data(mp3Path, fileData);
			Mp3 mp3 = new Mp3();
			mp3.FileName = mp3Path;
			mp3.play();
		}
		
		bool LvPublicFileListGetSelectedMp3(out TidPosition pos, out byte[] fileData)
		{
			pos = new TidPosition(0, 0, 0);
			fileData = new byte[0];
			
			if (lvPublicFileList.SelectedIndices.Count > 0)
			{
				int index = lvPublicFileList.SelectedIndices[0];
				int i = 0;
				foreach (KeyValuePair<TidPosition, byte[]> onefile in oneFile.PublicFileList)
				{
					if (index == i)
					{
						pos = onefile.Key;
						fileData = onefile.Value;
						break;
					}
					i++;
				}
				return true;
			}
			return false;
		}
		
		void LvPublicFileListPlaySelectedMp3()
		{
			TidPosition pos;
			byte[] fileData;
			if (LvPublicFileListGetSelectedMp3(out pos, out fileData))
			{
				PlayOneMp3Data(pos.fileNumber, fileData);
			}
		}
		
		void LvPublicFileListSaveSelectedMp3()
		{
			TidPosition pos;
			byte[] fileData;
			if (LvPublicFileListGetSelectedMp3(out pos, out fileData))
			{
				string mp3Path = GetOneSaveFilename("导出文件", "", pos.fileNumber.ToString() + ".mp3", ".mp3", "MP3文件|*.mp3|所有文件|*.*");
				if (mp3Path.Length == 0)
					return;
			
				SaveOneMp3Data(mp3Path, fileData);
			}
		}
		
		void BtnSaveClick(object sender, EventArgs e)
		{
//			BaiduTTS tts = new BaiduTTS();
//			byte[] fileData = tts.GetVoice("大家好，我是百度语音测试001");
//			PlayOneMp3Data(1, fileData);
			if (oneFile != null)
			{
				string newFile = tbTIDFile.Text + ".new";
				TidFileWriter tfw = new TidFileWriter(newFile, oneFile);
				tfw.WriteAll();
			}
		}
		
		void LvPrivateFileListMouseClick(object sender, MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Left)
			{
				LvPrivateFileListPlaySelectedMp3();
			}
			else if (e.Button == MouseButtons.Right)
			{
				cmsMp3Item.Show();
			}
		}
		
		void LvPublicFileListMouseClick(object sender, MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Left)
			{
				LvPublicFileListPlaySelectedMp3();
			}
			else if (e.Button == MouseButtons.Right)
			{
				cmsMp3Item.Show();
			}
		}
		
		void TsmiPlayClick(object sender, EventArgs e)
		{
			if (tcMain.SelectedIndex == 1)
			{
				LvPrivateFileListPlaySelectedMp3();
			}
			else if (tcMain.SelectedIndex == 2)
			{
				LvPublicFileListPlaySelectedMp3();
			}
		}
		
		void TsmiExportClick(object sender, EventArgs e)
		{
			if (tcMain.SelectedIndex == 1)
			{
				LvPrivateFileListSaveSelectedMp3();
			}
			else if (tcMain.SelectedIndex == 2)
			{
				LvPublicFileListSaveSelectedMp3();
			}
		}
		
		void TsmiReplaceClick(object sender, EventArgs e)
		{
			if (tcMain.SelectedIndex == 1)
			{
				if (ofdMain.ShowDialog() == DialogResult.OK)
				{
					string mp3Path = ofdMain.FileName;
					BinaryReader br = new BinaryReader(new FileStream(mp3Path, FileMode.Open));
					int fileLen = (int)br.BaseStream.Length;
					byte[] fileData = br.ReadBytes(fileLen);
					br.Close();
					
					LvPrivateFileListSetSelectedMp3(fileData);
				}
			}
			else if (tcMain.SelectedIndex == 2)
			{
				//TODO aaa
			}
		}
		
		void TsmiRemoveClick(object sender, EventArgs e)
		{
			if (tcMain.SelectedIndex == 1)
			{
				//TODO aaa
			}
			else if (tcMain.SelectedIndex == 2)
			{
				//TODO aaa
			}
		}
		
		void TsmiRemoveRightClick(object sender, EventArgs e)
		{
			if (tcMain.SelectedIndex == 1)
			{
				LvPrivateFileListPlaySelectedMp3();
			}
			else if (tcMain.SelectedIndex == 2)
			{
				LvPublicFileListPlaySelectedMp3();
			}
		}
	}
}
